/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if(head==nullptr || head->next==nullptr)
        {
            return head;
        }
        ListNode one(-1);
        ListNode* first=&one;
        first->next=head;
        ListNode* prev=first;
        ListNode* ptr=prev;
        ListNode* cur=ptr->next;
        while(cur)
        {
            if(cur->val<x && prev==ptr)
            {
                prev=prev->next;
                cur=cur->next;
                ptr=ptr->next;
            }else if(cur->val<x && prev!=ptr)
            {
                ptr->next=cur->next;
                cur->next=prev->next;
                prev->next=cur;

                cur=ptr->next;
                prev=prev->next;
            }else{
                cur=cur->next;
                ptr=ptr->next;
            }
        }
        return first->next;
    }
};